package com.basic.hellorabbit.util;

import com.basic.hellorabbit.entity.Student;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
* @Description:    json数据转换测试
* @Author:         Joe
* @CreateDate:     2020/3/18 16:21
*/
public class JsonTest {

    public static void main(String[] args) {
        //创建学生
        Student student01 = new Student(1,"亚瑟");
        Student student02 = new Student(2,"后羿");
        System.out.println("student01:"+student01+",student02:"+student02);
        List<Student> students01 = new ArrayList<>();
        Map<String,String> maps = new HashMap<>();
        maps.put("name1","妲己");
        maps.put("name2","甄姬");
        maps.put("name3","小乔");

        students01.add(student01);
        students01.add(student02);
        System.out.println("-----------------------------------------------------------------");
        System.out.println("maps："+maps);
        System.out.println("students01："+students01);
        System.out.println("------------------------------开始测试 -----------------------------------");

        //1.测试javaBean转json
        Gson gson1 = new Gson();
        String s1 = gson1.toJson(student01);
        System.out.println("javaBean转json："+s1);
        System.out.println("-----------------------------------------------------------------");

        //2.测试json转javaBean
        String json2 = s1;
        Gson gson2 = new Gson();
        Student student2 = gson2.fromJson(json2, Student.class);
        System.out.println("json转javaBean："+student2);
        System.out.println("-----------------------------------------------------------------");

        //3.List集合转为Json字符串
        Gson gson3 = new Gson();
        String listToJson3 = gson3.toJson(students01);
        System.out.println("List集合转为Json字符串："+listToJson3);
        System.out.println("-----------------------------------------------------------------");

        //4.Json字符串转为List集合
        String studentList4 = listToJson3;
        Gson gson4 = new Gson();
        List<Student> students4 = gson4.fromJson(studentList4, new TypeToken<List<Student>>() {
        }.getType());
        System.out.println("Json字符串转为List集合："+students4);
        System.out.println("-----------------------------------------------------------------");


        //5.Map转为Json字符串
        Gson gson5 = new Gson();
        String mapjson = gson5.toJson(maps);
        System.out.println("Map转为Json字符串："+mapjson);
        System.out.println("-----------------------------------------------------------------");

        //6.Json字符串转为Map
        Gson gson6 = new Gson();
        Map jsonmap = gson6.fromJson(mapjson, Map.class);
        System.out.println("Json字符串转为Map："+jsonmap);
    }
}
